サンプル JavaScript
Canvas は JavaScript で描画する。
記述例
var my_num = 1;
function init(){
draw();
IntervalID = setInterval('draw()',100);
}
//function stopdraw(){clearInterval(IntervalID);}
function draw() {
my_num ++;
if(my_num == 160){
// stopdraw();
my_num = 1;
}
var canvas = document.getElementById('my_canvas');
if ( ! canvas || ! canvas.getContext ) { return false;}
/* 四角(空)*/
var my_ctx = canvas.getContext('2d');
my_ctx.clearRect(0,0,300,160);//-------clear
var gradsk = my_ctx.createLinearGradient(0,0,0,80);
gradsk.addColorStop(0,'LightBlue');
gradsk.addColorStop(1,'white');
my_ctx.save();//-------save
my_ctx.fillStyle = gradsk;
my_ctx.beginPath();
my_ctx.rect(0,0,300,80);
my_ctx.fill();
my_ctx.restore();//-------restore
/* 円(太陽) */
var my_ctx = canvas.getContext('2d');
var gradci = my_ctx.createLinearGradient(0,(my_num-30),0,(30+my_num));
gradci.addColorStop(0,'#FF0000');
gradci.addColorStop(1,'#FFFF33');
my_ctx.save();//-------save
my_ctx.fillStyle = gradci;
my_ctx.beginPath();
my_ctx.arc(60, my_num, 30, 0, Math.PI*2, false);
my_ctx.fill();
my_ctx.restore();//-------restore
/* 山 */
var my_ctx= canvas.getContext('2d');
var gradmo = my_ctx.createRadialGradient(150,200,120,150,200,160);
gradmo.addColorStop(0,'#336699');
gradmo.addColorStop(1,'#FFFFFF');
my_ctx.save();//-------save
my_ctx.fillStyle = gradmo;
my_ctx.beginPath();
my_ctx.moveTo(140,20);
my_ctx.lineTo(160,20);
my_ctx.lineTo(280,160);
my_ctx.lineTo(20,160);
my_ctx.closePath();
my_ctx.fill();
my_ctx.restore();//-------restore
}