使用可滚动的画布窗口绘制线条

Draw line with scrollable canvas window

本文关键字:窗口 绘制 布窗口 滚动      更新时间:2023-09-26

我是画布的新人。我想知道如何用可滚动的画布画一条线,window.my 期望是画布窗口适合屏幕,如果线转到视口的外侧,那么画布窗口是可滚动的,直到查看行的末尾。谢谢。


<html>
<head>
<head>
<body>
<canvas id="myCanvas" style="border:1px solid #d3d3d3;float: left;" > Your browser does not support the HTML5 canvas tag.</canvas>
<script>
function draw() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(1500,1000);
ctx.stroke();
}
draw();
</script>
</body>
</html>

您可以让浏览器添加滚动条,方法是将较高的画布包装在较短的div 中并设置较短的div 的overflow:scroll

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,1000);
ctx.stroke();
body{ background-color: ivory; }
#viewport{width:320px;height:150px;border:1px solid blue;overflow:scroll;}
#canvas{border:1px solid red; }
<div id=viewport>
  <canvas id="canvas" width=300 height=1500></canvas>
</div>