Canvas 图形变换
位移 translate(x,y)
旋转 rotate(deg)
缩放 scale(sx,sy)
save()
restore()
位移
window.onload = function () {
var canvas = document.getElementById('canvas')
canvas.width = 800
canvas.height = 800
var context = canvas.getContext('2d')
context.save() //保存
context.fillStyle = 'red'
context.translate(100, 100)
context.fillRect(0, 0, 400, 400)
context.restore() //清除上面位移所有的状态
//画一个绿色的 这个时候也位移了,但是位移叠加,所以为了防止这个情况必须位移消除
context.save() //保存
context.fillStyle = 'green'
context.translate(300, 300)
context.fillRect(0, 0, 400, 400)
context.translate(-300, -300)
context.restore()
}
旋转
window.onload = function () {
var canvas = document.getElementById('canvas')
canvas.width = 800
canvas.height = 800
var context = canvas.getContext('2d')
context.save() //保存
context.rotate((20 * Math.PI) / 180)
context.restore() //清除状态
}
放大和缩小
window.onload = function () {
var canvas = document.getElementById('canvas')
canvas.width = 800
canvas.height = 800
var context = canvas.getContext('2d')
context.save() //保存
context.scale(2, 2) //放大 线条的宽度也会放大
context.restore() //清除状态
}