我正在尝试获取放置在标记下的myCanvas的上下文,当我尝试获取上下文值时,我收到错误,说明画布未定义???我该如何解决这个问题?
提前致谢。 这是我的代码:
HTML:
< body >
< div class ="div-left-column" id ="display" onload="make_base()" >
< img id="scream" src="/home/openstack/harikrishna/html/tower.jpg" alt="The Scream" width="50" height="50" >
< img id ="gray" src ="/home/openstack/harikrishna/html/tower-gray.jpg" width = 50 height = 50/ >
< canvas id="myCanvas" width="800" height="500" style="border:1px solid #d3d3d3;" />
< input type ="button" id="clear" name ="clear" value ="clear" />
< /div >
< /body >
JS:
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
e = GetElementInsideContainer("display", "myCanvas");
var canvas = e.id;
var ctx = canvas.getContext("2d");
var image = document.getElementById("scream");
var clicks = 0;
var lastClick = [0, 0];
canvas.addEventListener("dblclick", getPosition, false);
function make_base(){
var img = new Image();
var img2 = new Image();
img.src = "/home/openstack/harikrishna/html/tower.jpg";
img2.src = "/home/openstack/harikrishna/html/tower-gray.jpg";
img.onload = function(){
ctx.drawImage(img, 10,10,30,30);
ctx.beginPath();
ctx.moveTo(40,40);
ctx.lineTo(80,250);
ctx.stroke();
ctx.drawImage(img, 80,250,30,30);
ctx.beginPath();
ctx.moveTo(110,250);
ctx.lineTo(210,20);
ctx.stroke();
ctx.drawImage(img,180,20,30,30);
}
img2.onload = function(){
ctx.drawImage(img2,250,200,30,30);
}
}
function getPosition(event)
{
var x = event.x;
var y = event.y;
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
//alert("x:" + x + " y:" + y);
ctx.clearRect(250,200,30,30);
ctx.drawImage(image,x,y,30,30);
}
document.getElementById('clear').addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, false);
答案 0 :(得分:0)
答案 1 :(得分:0)
您只提到了ID元素而不是DOM元素。
代码:
e = GetElementInsideContainer("display", "myCanvas");
console.log(e.id); //here geeting only id name
var canvas = document.getElementById(e.id);
console.log(canvas); //here geeting only DOM element
var ctx = canvas.getContext("2d");