2019年12月2日 星期一

AJAX send Canvas 建立的圖片

要將Canvas 建立的圖片做其他處理,例如傳AJAX 基本上就是利用 HTML5 新增的 Blob 來處理 首先建立 Canvas
var canvas = document.createElement("canvas")
var ctx = canvas.getContext("2d")

canvas.width = 125
canvas.height = 125

ctx.fillStyle = "navy"
ctx.fillRect(25,25,100,100)
ctx.clearRect(45,45,60,60)
ctx.strokeStyle = "purple"
ctx.strokeRect(50,50,50,50)
利用 Canvas 建立 Blob Object
canvas.toBlob(function(blob){
	// ...
}
傳送 AJAX
//假設這邊還有其他表單欄位要傳送,所以建立 FormData Object
var f = new FormData 
f.set("data", blob) // 傳入剛才建立的圖片 Object
f.set("date", Date.now())
f.set("name", "test blob")

var u = "/upload" // 我們要傳送的 Request URL

// Send Ajax
var xhr = new XMLHttpRequest

xhr.onreadystatechange = function(){
	switch(this.readystate){
		case XMLHttpRequest.DONE:
			console.log("Send Successfully")
			break;
	}
}

xhr.open("POST", u)
xhr.send(f)
或者使用 HTML 5 的 fetch API(使用前請確認瀏覽器是否真的能支援 fetch API)
fetch(u, {method:"POST", body: f})
	.then(response => {
		if (response.ok){
			return response
		}
		else throw Error(`Server returned ${response.status}: ${response.statusText}`)
	})
	.then(response => console.log(response.text()))
	.catch(err => {
		console.error(err);
	});
抑或使用 jQuery
$.ajax({
	url: u,
	method: "post",
	contentType: false,
	processData: false,
	data: f,
	success: function(data,status){
		console.log("Send Successfully")
	},
});

最後的 Code 如下:
var canvas = document.createElement("canvas")
var ctx = canvas.getContext("2d")

canvas.width = 125
canvas.height = 125

ctx.fillStyle = "navy"
ctx.fillRect(25,25,100,100)
ctx.clearRect(45,45,60,60)
ctx.strokeStyle = "purple"
ctx.strokeRect(50,50,50,50)


canvas.toBlob(function(blob){
	var f = new FormData 
	f.set("data", blob)
	f.set("date", Date.now())
	f.set("name", "test blob")
	
	var u = "/upload" 

	var xhr = new XMLHttpRequest

	xhr.onreadystatechange = function(){
		switch(this.readystate){
			case XMLHttpRequest.DONE:
				console.log("Send Successfully")
				break;
		}
	}

	xhr.open("POST", u)
	xhr.send(f)
}

沒有留言:

張貼留言