如何将画布放入页面上的特定位置?例如,我想在ascii“电视屏幕”中找到画布。我怎么能这样做?
由于
o o / \ / \ / \ / +--------------------v--------------------------+ | ______________________________________ @| | / \ | | | | (\) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | (-) | | | | | | \ / :|||: | | -ooo--------------------------------- :|||: | +-----------------------------------------------+ [] []
答案 0 :(得分:3)
您可以使用合成将绘图限制在电视屏幕
优点:
它的工作原理如下:
在画布上绘制电视图像:
ctx.drawImage(tv,0,0,tv.width,tv.height);
关于此电视图像的重要之处在于屏幕具有透明像素
在向屏幕绘制任何内容之前,请将合成设置为“destination-over”。这会导致画布保留已经在屏幕(电视)上绘制的任何非透明像素,并且仅绘制到透明像素(您的电视屏幕)。
结果:你只能画到电视的屏幕上。其余的电视都保存完毕。
ctx.globalCompositeOperation="destination-over";
这是代码和小提琴:http://jsfiddle.net/m1erickson/7JPrx/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: white; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var tv=new Image();
var land=new Image();
tv.onload=function(){
land.onload=function(){
draw();
}
land.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape.png";
}
tv.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/tv1.png";
var offsetX=0;
function draw(){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw the tv
// NOTE: the screen of the tv must be transparent
ctx.drawImage(tv,0,0,tv.width,tv.height);
// begin drawing the screen
ctx.save();
ctx.beginPath();
// this causes any drawing to ONLY draw over transparent pixels
// that's how we draw within the screen because
// the screen is the only part of the tv with transparent pixels
ctx.globalCompositeOperation="destination-over";
// move (translate) our drawing to the screen part of the tv image
ctx.translate(32,95);
// draw the landscape scrolling across the screen (using offsetX)
ctx.drawImage(land,offsetX,0);
// reset
ctx.restore();
offsetX-=10;
if(offsetX<=-600){offsetX=0;}
setTimeout(draw,100);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
答案 1 :(得分:1)
您只需使用css命令设置画布位置
即可position:relative; or position:absolute;
e.g
canvas{
position:relative;
top:Ypx;
left:Xpx;
}