html5 scrolling,javascript - Horizontal Scrolling on Canvas. HTML5 - Stack Overflow

电玩女神 2022-10-09 05:57 117阅读 0赞

Here’s a pretty basic implementation: http://jsfiddle.net/CQPeU/

var can = document.getElementById(“can”),

ctx = can.getContext(‘2d’),

dragging = false,

lastX = 0,

translated = 0;

// these two lines will make the y-axis grow upwards.

ctx.scale(1,-1);

ctx.translate(0, -400);

can.onmousedown = function(e){

var evt = e || event;

dragging = true;

lastX = evt.offsetX;

}

window.onmousemove = function(e){

var evt = e || event;

if (dragging){

var delta = evt.offsetX - lastX;

translated += delta;

ctx.translate(delta, 0); // translate the context.

lastX = evt.offsetX;

draw(); // redraw

}

}

window.onmouseup = function(){

dragging = false;

}

function draw() {

ctx.clearRect(-translated, 0, 600, 400); // this is why we need to keep track of how much we’ve translated

for (var i = 0; i < plot.length; i++) {

ctx.beginPath();

ctx.arc(plot[i].x, plot[i].y, 5, 0, 2 * Math.PI); // note we don’t have to futz with the x/y values, and can use them directly.

ctx.fill();

}

}

To create a grid, you could do something like this:

var grid = (function(dX, dY){

var can = document.createElement(“canvas”),

ctx = can.getContext(‘2d’);

can.width = dX;

can.height = dY;

// fill canvas color

ctx.fillStyle = ‘black’;

ctx.fillRect(0, 0, dX, dY);

// x axis

ctx.strokeStyle = ‘orange’;

ctx.moveTo(.5, 0.5);

ctx.lineTo(dX + .5, 0.5);

ctx.stroke();

// y axis

ctx.moveTo(.5, .5);

ctx.lineTo(.5, dY + .5);

ctx.stroke();

return ctx.createPattern(can, ‘repeat’);

})(100, 50);

Which would be used like this:

function draw() {

ctx.clearRect(-translated, 0, 600, 400);

ctx.rect(-translated, 0, 600, 400);

ctx.fillStyle = grid;

ctx.fill();

ctx.fillStyle = “#fff”;

for (var i = 0; i < plot.length; i++) {

ctx.beginPath();

ctx.arc(plot[i].x, plot[i].y, 5, 0, 2 * Math.PI);

ctx.fill();

}

}

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HTML5】——Canvas

    Canvas是HTML5中所有新特性中目前应用最广泛的一个,可以替代引入的图片(图形) 用途:完成HTML页面中的图形绘制,实现网络游戏或单击游戏(网页游戏),在HTML中