javascript - 使用可滚动 Canvas 窗口绘制线条

标签 javascript html canvas

我是 Canvas 新手。我想知道如何使用可滚动 Canvas 窗口绘制一条线。我的期望是 Canvas 窗口适合屏幕,如果线条移到视口(viewport)的外侧,则 Canvas 窗口可以滚动,直到查看行尾。我尝试此代码。对此问题有任何想法。谢谢。

<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>

最佳答案

您可以通过将较高的 Canvas 包裹在较短的 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>

关于javascript - 使用可滚动 Canvas 窗口绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161137/

相关文章:

javascript - Windows 中的 JScript 或 JQuery

javascript - Bar Chart.js 不显示 PHP、MySQL、AJAX 的值

HTML 必填输入字段气泡关闭位置(谷歌浏览器)?

javascript - 在 HTML 中映射色彩空间

javascript - 使用 HTML 5 和 Canvas 构建图像编辑器

javascript - 算法在一个非常大的数组中查找重复项

javascript - 整洁的内容转换,如 HTML5 bing

html - CSS 动画条纹不起作用

javascript - 如何使用javascript更新css过滤器中的明亮值而不删除其他过滤器属性。?

HTML5 : Inverse text-color on canvas