2012-01-08 47 views
3

我无法找到html5画布的答案。我是否可以更改原点的坐标,以便我的图元完全移动到15px的右侧(仅作为示例)。鉴于以下的HTML和CSS?如何更改html5画布的来源?

<canvas id="g" width="auto" height="auto">Your browser doesnt support canvas tag</canvas> 

CSS:

canvas, section { 
    display: block; 
}  

#g { 
    position: absolute; 
    width:100%; 
    height:100%; 
    overflow:hidden; 
} 
+0

正在重绘整个上下文一个选项?或者你只是想用CSS移动canvas元素? – arahaya 2012-01-08 22:41:28

+0

@arahaya重绘会很棒! – Jurudocs 2012-01-08 22:59:17

回答

11

听起来像是你需要一个translate transform。根据你在上下文中做什么,你可能还需要拨打save() and restore()

var ctx = document.getElementById('myCanvas').getContext('2d'); 
ctx.save(); 
ctx.translate(15, 0); 
// ... do stuff with the transformed origin 
ctx.restore(); 
// ... do stuff with the canvas restored to its original state (if necessary) 
+0

请注意,如果需要,您可以通过调用'resetTransform()'来重置原点,而不是尝试通过所有更改进行“翻译”。有关详细信息,请参见[MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/resetTransform)。 – brichins 2016-07-21 19:06:37