Javascript HTML5画布,另存为图像,toDataURL(),创建ID
我有一个小小的JavaScript画布片段:Javascript HTML5画布,另存为图像,toDataURL(),创建ID,javascript,html,canvas,Javascript,Html,Canvas,我有一个小小的JavaScript画布片段: (function() { // Creates a new canvas element and appends it as a child // to the parent element, and returns the reference to // the newly created canvas element function createCanvas(parent, width, height) {
(function() {
// Creates a new canvas element and appends it as a child
// to the parent element, and returns the reference to
// the newly created canvas element
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var radius = 10; // or whatever
var fillColor = '#ff0000';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}
var container = document.getElementById('canvas');
init(container, 200, 200, '#ddd');
})();
现在它使用canvas
的id
获取div,并在其中创建一个小的HTML5canvas
,用户基本上可以用鼠标进行绘制。现在这很好。。。但是如果我必须使用canvas.toDataURL()
保存画布中的内容,该怎么办?据我所知,我必须使用画布,然后执行canvas.toDataURL()
将其保存到图像中。但是-那需要一个身份证,对吗?所以,当我在createCanvas
函数中创建画布时,我应该如何制作一个id
,这样我就可以执行类似document.getElementById(“idofcanvas”).toDataURL()的操作了
提前感谢您的帮助!:)
但是-那需要一个身份证,对吗
它不需要ID,但ID不会有任何伤害(只要它实际上是唯一的;-)
)。任何选择DOM元素的方法都可以在这里使用。如果页面上只有一个画布,这就足够了,例如:
var canvas = document.getElementsByTagName('canvas')[0];
var imageData = canvas.toDataURL();
当我在createCanvas函数中创建画布时,我将如何制作一个伴随它的id
您只需在返回canvas元素之前设置其ID属性。请记住,您需要确保此值是唯一的
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.node.id = /* some unique value here */;
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
如果页面上有多个画布,则可以将搜索包含到document.getElementById('canvas').getElementsByTagName('canvas')[0])
。我没有注意到画布被附加到了
。非常感谢您的帮助^_^哦,我刚才看到了你剩下的答案。:)太酷了!:)不知道您可以用canvas.node.id
!:)更改id太棒了!:)但它确实有意义,就像canvas.node.style
或canvas.node.value
或其他东西一样。对我来说是愚蠢的时刻!:)非常感谢@user2049022我不认为你真的需要生成一个ID。您希望能够在代码中的何处调用canvas.toDataURL()
?