Javascript JS画布显示在页面底部
我有这个代码,我想使用箭头作为标题中的徽标。当我在标题中实现这段代码时,不管发生什么情况,它都会呈现在页面的最底部 我尝试了不同的css类来移动画布,但似乎没有任何效果。我还尝试在我想要的地方硬编码画布,但没有这样做 请给这个新手点什么帮助?:) 提前谢谢Javascript JS画布显示在页面底部,javascript,canvas,Javascript,Canvas,我有这个代码,我想使用箭头作为标题中的徽标。当我在标题中实现这段代码时,不管发生什么情况,它都会呈现在页面的最底部 我尝试了不同的css类来移动画布,但似乎没有任何效果。我还尝试在我想要的地方硬编码画布,但没有这样做 请给这个新手点什么帮助?:) 提前谢谢 var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = 100; canvas.height = 100
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 100;
canvas.height = 100;
document.body.appendChild(canvas);
var renderSaveCount = 0; // Counts the number of mouse events that we did not have to render the whole scene
var arrow = {
x : 40,
y : 40,
image : new Image()
};
var mouse = {
x : null,
y : null,
changed : false,
changeCount : 0,
}
arrow.image.src = 'http://www.jeroenmigneaux.com/Untitled-2.png';
function drawImageLookat(img, x, y, lookx, looky){
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.rotate(Math.atan2(looky - y, lookx - x) - Math.PI / 2); // Adjust image 90 degree anti clockwise (PI/2) because the image is pointing in the wrong direction.
ctx.drawImage(img, -img.width / 2, -img.height / 2);
ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default not needed if you use setTransform for other rendering operations
}
function drawCrossHair(x,y,color){
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(x - 10, y);
ctx.lineTo(x + 10, y);
ctx.moveTo(x, y - 10);
ctx.lineTo(x, y + 10);
ctx.stroke();
}
function mouseEvent(e) { // get the mouse coordinates relative to the canvas top left
var bounds = canvas.getBoundingClientRect();
mouse.x = e.pageX - bounds.left;
mouse.y = e.pageY - bounds.top;
mouse.cx = e.clientX - bounds.left; // to compare the difference between client and page coordinates
mouse.cy = e.clienY - bounds.top;
mouse.changed = true;
mouse.changeCount += 1;
}
document.addEventListener("mousemove",mouseEvent);
var renderTimeTotal = 0;
var renderCount = 0;
ctx.font = "18px arial";
ctx.lineWidth = 1;
// only render when the DOM is ready to display the mouse position
function update(){
if(arrow.image.complete && mouse.changed){ // only render when image ready and mouse moved
var now = performance.now();
mouse.changed = false; // flag that the mouse coords have been rendered
ctx.clearRect(0, 0, canvas.width, canvas.height);
// get mouse canvas coordinate correcting for page scroll
var x = mouse.x - scrollX;
var y = mouse.y - scrollY;
drawImageLookat(arrow.image, arrow.x, arrow.y, x ,y);
// draw mouse event client coordinates on canvas
drawCrossHair(mouse.cx,mouse.cy,"rgba(255,100,100,0.2)");
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
我认为,在没有看到实际html的情况下,这是由于以下原因造成的:
document.body.appendChild(canvas);
您将画布附加到主体,而您可以将其附加到header元素。正文一直到页面底部
为了清楚起见:
document.getElementById('headerId').appendChild(canvas);
工作起来很有魅力!谢谢你的帮助。:)