绘图并保留 HTML5 canvas 上的更改

Drawing and retain the changes on HTML5 canvas

我应该可以在图片上画画并保存。我想知道是否有可能允许用户仅在地图(形状)上绘制? 这是完整的代码: http://codepen.io/anon/pen/VYOXRW

var ctx, color = '#FF0000';
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
    newCanvas();
}, 1000);
}, false);
 function newCanvas() {
document.getElementById("content").style.height = window.innerHeight + 100;
var canvas = '<canvas id="canvas" width="' + window.innerWidth + '" height="' + (window.innerHeight + 50) + '"></canvas>';
document.getElementById("content").innerHTML = canvas;
ctx = document.getElementById("canvas").getContext("2d");
ctx.strokeStyle = color;
ctx.lineWidth = 10;
var image = new Image();
image.src = 'http://4.bp.blogspot.com/-_laBnztzAG8/Ub7mDK4Z3qI/AAAAAAAABu4/LBPUeAVeJcc/s1600/CA+KATHMANDU+VALLEY_HU.png';
image.onload = function() {
    var canvas = document.getElementById("canvas");
    var iWidth = image.width / 3;
    var iHeight = image.height / 3;
    ctx.drawImage(image, (canvas.width - iWidth) / 2, (canvas.height - iHeight) / 2, iWidth, iHeight);
};
drawTouch();
drawMouse();
}
 function selectColor(el) {
color = window.getComputedStyle(el).color;
ctx.beginPath();
ctx.strokeStyle = color;
}
 var drawTouch = function() {
var start = function(e) {
    ctx.beginPath();
    x = e.changedTouches[0].pageX;
    y = e.changedTouches[0].pageY;
    ctx.moveTo(x, y);
};
var move = function(e) {
    e.preventDefault();
    x = e.changedTouches[0].pageX;
    y = e.changedTouches[0].pageY;
    ctx.lineTo(x, y);
    ctx.stroke();
};
document.getElementById("canvas").addEventListener("touchstart", start, false);
document.getElementById("canvas").addEventListener("touchmove", move, false);
 };
var drawMouse = function() {
var clicked = 0;
var start = function(e) {
    clicked = 1;
    ctx.beginPath();
    x = e.pageX;
    y = e.pageY;
    ctx.moveTo(x, y);
};
var move = function(e) {
    if (clicked) {
        x = e.pageX;
        y = e.pageY;
        ctx.lineTo(x, y);
        ctx.stroke();
    }
};
var stop = function(e) {
    clicked = 0;
};
document.getElementById("canvas").addEventListener("mousedown", start, false);
document.getElementById("canvas").addEventListener("mousemove", move, false);
document.addEventListener("mouseup", stop, false);
};
 function saveBtn() {
console.log(document.getElementById('canvas').toDataURL());
}

当您希望用户能够以非破坏性方式在图像上绘图时,您可以创建第二个 canvas 并使用 CSS 定位将其放置在首先canvas。用户现在可以在上面的 canvas 上自由绘制,而下面的 canvas 不受影响并且仍然可以通过任何 alpha 透明区域看到(顺便说一句,当你不打算做任何 canvas-在后台进行所有操作,您也可以使用普通的旧 <img>).

如果您想将两个 canvases 变成一个可以保存的图像,请创建一个新的屏幕外 canvas 并用 canvases 绘制它 drawImage(是的,drawImage 可以使用 <canvas> 作为源,就像它可以使用 <img> 一样)。然后,您可以使用 canvas.toDataURL 获取 canvas 内容的 PNG 或 JPEG 压缩和 base64 编码字符串。然后,您可以根据需要存储该字符串。