我正在尝试删除现有的画布,并创建一个具有修改后内容(旧内容)的新画布。
下面是我尝试过的代码。
/ *标识div父级内部的Canvas子级* /
var c = document.getElementById("myCanvasDiv"),
canv = '',
cv = '';
for (i = 0; i < c.childElementCount; i++) {
console.log(c.children[i].nodeName);
if (c.children[i].nodeName == "CANVAS") {
//console.log(c.children[i].getContext('2d'));
canv = c.children[i];
cv = c.children[i].getContext('2d');
}
}
var new_cv = cv
var items = new_cv.canvas.aa.nodes.bi.ud
var keys = []
/ *检索键* /
for (var i in items){
//console.log(items[i].value.Zd["key"]);
keys.push(i + "|" +items[i].value.Zd["key"]);
}
/ *修改内容* /
for (var i in items){
var strVal = items[i].value.Zd["key"];
//console.log(items[i].value.Zd["key"]);
for (var j in keys){
if(items[i].value.Zd["key"] && items[i].value.Zd["key"].substring(0,items[i].value.Zd["key"].length-1) == keys[j].split("|")[1]){
items[i].value.Zd["key"] = keys[j].split("|")[1];
}
}
console.log(strVal + "----->" + items[i].value.Zd["key"]);
}
/ *试图重置画布内容* /
for (i = 0; i < c.childElementCount; i++) {
if (c.children[i].nodeName == "CANVAS") {
/*c.removeChild(c.children[i]);
var newcanvas = document.createElement("canvas");
newcanvas.id="canvas1";
newcanvas.getContext = new_cv;
c.appendChild(newcanvas);*/
//cHeight = c.children[i].height;
//cWidth = c.children[i].width;
//cv.clearRect(0,0,c.children[i].width,c.children[i].height);
//c.children[i] = new_cv;
//cv.setContext(new_cv);
canv.getContext = new_cv;
console.log(cv);
}
}
有什么办法可以实现这一目标。
谢谢。
答案 0 :(得分:0)
最简单的方法是:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
ctx.clearRect(0,0, c.width, c.height);
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 50, 50);
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<button onclick="copy()">Copy</button>
<p id="cont"> FillStyle Content</p>
但是,如果您要使用像素处理(价格昂贵得多),则可以执行以下操作:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
// for every pixel if the red channel value is 255 (i.e. red) then make it black (0)
for (var i = 0; i < imgData.data.length; i += 4) {
if (imgData.data[i + 0] == 255) {
imgData.data[i + 0] = 0;
}
}
// put the modified image back
ctx.putImageData(imgData, 0, 0);
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<button onclick="copy()">Copy</button>
<p id="cont"> FillStyle Content</p>