簡體   English   中英

使畫布充當按鈕

[英]Make Canvas Act as a Button

我想要的是有一個按鈕,而按鈕的背景是畫布。 這是我的按鈕代碼:

 //Lets create a simple particle system in HTML5 canvas and JS //Initializing the canvas var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //Canvas dimensions var W = 500; var H = 500; //Lets create an array of particles var particles = []; for(var i = 0; i < 50; i++) { //This will add 50 particles to the array with random positions particles.push(new create_particle()); } //Lets create a function which will help us to create multiple particles function create_particle() { //Random position on the canvas this.x = Math.random()*W; this.y = Math.random()*H; //Lets add random velocity to each particle this.vx = Math.random()*20-10; this.vy = Math.random()*20-10; //Random colors var r = Math.random()*255>>0; var g = Math.random()*255>>0; var b = Math.random()*255>>0; this.color = "rgba("+r+", "+g+", "+b+", 0.5)"; //Random size this.radius = Math.random()*20+20; } var x = 100; var y = 100; //Lets animate the particle function draw() { //Moving this BG paint code insde draw() will help remove the trail //of the particle //Lets paint the canvas black //But the BG paint shouldn't blend with the previous frame ctx.globalCompositeOperation = "source-over"; //Lets reduce the opacity of the BG paint to give the final touch ctx.fillStyle = "rgba(0, 0, 0, 0.3)"; ctx.fillRect(0, 0, W, H); //Lets blend the particle with the BG ctx.globalCompositeOperation = "lighter"; //Lets draw particles from the array now for(var t = 0; t < particles.length; t++) { var p = particles[t]; ctx.beginPath(); //Time for some colors var gradient = ctx.createRadialGradient(px, py, 0, px, py, p.radius); gradient.addColorStop(0, "white"); gradient.addColorStop(0.4, "white"); gradient.addColorStop(0.4, p.color); gradient.addColorStop(1, "black"); ctx.fillStyle = gradient; ctx.arc(px, py, p.radius, Math.PI*2, false); ctx.fill(); //Lets use the velocity now px += p.vx; py += p.vy; //To prevent the balls from moving out of the canvas if(px < -50) px = W+50; if(py < -50) py = H+50; if(px > W+50) px = -50; if(py > H+50) py = -50; } } setInterval(draw, 33); //I hope that you enjoyed the tutorial :) 
 <button align=center> <canvas id="canvas"></canvas> <span id="submit">Submit</span> </button> 

由於某種原因,按鈕很大,我不知道為什么,但是,我希望我的文字在畫布上。 我怎樣才能做到這一點?

您需要指定畫布的大小。 您可以通過<canvas width="50" height="50"></canvas>屬性將畫布的寬度和高度設置為固定值來實現。 圖形受您可能還希望更改的width和height變量的約束。 至於文本,則需要使用絕對定位將其定位在畫布上。 或者,您可以直接在畫布上繪制文本。 請注意,您可以使用沒有按鈕的畫布,然后在畫布上注冊click事件處理程序以模擬按鈕。

https://jsfiddle.net/684vtxm1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM