在 Canvas 上创建滚动事件
Create Scrolling Event On Canvas
我有一个带有显示图表的 canvas 的弹出窗口,但有时图表比 canvas 大 有没有办法可以添加某种滚动事件以允许用户水平滚动以查看图表的其余部分?
Canvas
是像 img
一样的普通 DOM 元素,因此您可以使用常规 CSS 样式来定义滚动行为。例如:
$(document).ready(function(){
var ctx = $("#canvs").get(0).getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0,0,1600,300);
ctx.strokeStyle = "lime";
ctx.moveTo(0, 150);
for (var i = 0; i <= 16; i++){
var y = i % 2 == 0 ? 50 : 250;
ctx.lineTo(i * 100, y);
ctx.stroke();
}
});
#cont{
display: block;
width: 500px;
height: 330px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cont'>
<canvas id='canvs' width='1600px' height='300px'></canvas>
</div>
我有一个带有显示图表的 canvas 的弹出窗口,但有时图表比 canvas 大 有没有办法可以添加某种滚动事件以允许用户水平滚动以查看图表的其余部分?
Canvas
是像 img
一样的普通 DOM 元素,因此您可以使用常规 CSS 样式来定义滚动行为。例如:
$(document).ready(function(){
var ctx = $("#canvs").get(0).getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0,0,1600,300);
ctx.strokeStyle = "lime";
ctx.moveTo(0, 150);
for (var i = 0; i <= 16; i++){
var y = i % 2 == 0 ? 50 : 250;
ctx.lineTo(i * 100, y);
ctx.stroke();
}
});
#cont{
display: block;
width: 500px;
height: 330px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cont'>
<canvas id='canvs' width='1600px' height='300px'></canvas>
</div>