注意:canvas中变换的都是坐标系;
translate()平移坐标系:
<
script
>
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . translate ( 50 , 50 );
ctx . translate ( 50 , 50 );
ctx . strokeRect ( 0 , 0 , 300 , 200 );
ctx . beginPath ();
ctx . translate ( - 100 , - 100 );
ctx . strokeRect ( 0 , 0 , 300 , 200 );
</ script >
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . translate ( 50 , 50 );
ctx . translate ( 50 , 50 );
ctx . strokeRect ( 0 , 0 , 300 , 200 );
ctx . beginPath ();
ctx . translate ( - 100 , - 100 );
ctx . strokeRect ( 0 , 0 , 300 , 200 );
</ script >
rotate旋转坐标系
<
script
>
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . rotate ( Math . PI / 4 );
ctx . rotate ( - Math . PI / 4 );
ctx . strokeRect ( 0 , 0 , 300 , 200 );
</ script >
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . rotate ( Math . PI / 4 );
ctx . rotate ( - Math . PI / 4 );
ctx . strokeRect ( 0 , 0 , 300 , 200 );
</ script >
旋转示例:
<
script
>
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . strokeStyle = "pink" ;
//1 、平移坐标系到矩形的中心点
ctx . translate ( 150 , 100 );
var timer= setInterval ( function (){
ctx . rotate ( 0.01 * Math . PI );
//2 、绘制矩形
ctx . strokeRect ( - 150 , - 100 , 300 , 200 );
}, 10 );
</ script >
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . strokeStyle = "pink" ;
//1 、平移坐标系到矩形的中心点
ctx . translate ( 150 , 100 );
var timer= setInterval ( function (){
ctx . rotate ( 0.01 * Math . PI );
//2 、绘制矩形
ctx . strokeRect ( - 150 , - 100 , 300 , 200 );
}, 10 );
</ script >
scale伸缩变换
<
script
>
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
// 变成一个竖起来的椭圆
ctx . scale ( 0.5 , 1 );
ctx . arc ( 150 , 300 , 150 , 0 , 2 * Math . PI );
ctx . stroke ();
</ script >
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
// 变成一个竖起来的椭圆
ctx . scale ( 0.5 , 1 );
ctx . arc ( 150 , 300 , 150 , 0 , 2 * Math . PI );
ctx . stroke ();
</ script >
伸缩变换示例demo2
<
script
>
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . scale ( 0.5 , 0.5 );
ctx . strokeStyle = "red" ;
ctx . strokeRect ( 0 , 0 , 1600 , 1200 );
ctx . beginPath ();
ctx . strokeStyle = "blue" ;
ctx . strokeRect ( 0 , 0 , 800 , 600 );
</ script >
var canvas = document . getElementById ( "canvas" );
var ctx = canvas . getContext ( "2d" );
ctx . scale ( 0.5 , 0.5 );
ctx . strokeStyle = "red" ;
ctx . strokeRect ( 0 , 0 , 1600 , 1200 );
ctx . beginPath ();
ctx . strokeStyle = "blue" ;
ctx . strokeRect ( 0 , 0 , 800 , 600 );
</ script >