HTML5画布背景图片重复

前端之家收集整理的这篇文章主要介绍了HTML5画布背景图片重复前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个绘制声波的 html5画布.我将背景设置为背景图像,但是,我想要这个背景图像重复.任何人都可以告诉我如何做到这一点,我需要添加到我的代码中:
  1. var backgroundImage = new Image();
  2. backgroundImage.src = 'http://www.samskirrow.com/client-kyra/images/main-bg.jpg';
  3. var canvas;
  4. var context;
  5.  
  6. function init(c) {
  7. canvas = document.getElementById(c);
  8. context = canvas.getContext("2d");
  9. soundManager.onready(function() {
  10. initSound(clientID,playlistUrl);
  11. });
  12. aniloop();
  13. }
  14.  
  15. function aniloop() {
  16. requestAnimFrame(aniloop);
  17. drawWave();
  18. }
  19.  
  20. function drawWave() {
  21.  
  22. var step = 10;
  23. var scale = 60;
  24.  
  25. // clear
  26. context.drawImage(backgroundImage,0);
  27.  
  28. // left wave
  29. context.beginPath();
  30. context.moveTo(0,256);
  31. for ( var i = 0; i < 256; i++) {
  32. context.lineTo(6 * i,257 + waveLeft[i] * 80.);
  33. }
  34. context.lineWidth = 1;
  35. context.strokeStyle = "#000";
  36. context.stroke();
  37.  
  38. // right wave
  39. context.beginPath();
  40. context.moveTo(0,256 + waveRight[i] * 80.);
  41. }
  42. context.lineWidth = 1;
  43. context.strokeStyle = "#000";
  44. context.stroke();
  45. }
  46.  
  47. function updateWave(sound) {
  48. waveLeft = sound.waveformData.left;
  49. }
  50.  
  51. return {
  52. init : init
  53. };
  54. })();

您可以在此处查看此代码
http://www.samskirrow.com/client-kyra

解决方法

使用画布’ createPattern功能
  1. var canvas = document.getElementById("canvas"),context = canvas.getContext("2d"),img = new Image();
  2.  
  3. img.src = 'https://www.google.nl/images/srpr/logo3w.png';
  4.  
  5. img.onload = function(){
  6. // create pattern
  7. var ptrn = context.createPattern(img,'repeat'); // Create a pattern with this image,and set it to "repeat".
  8. context.fillStyle = ptrn;
  9. context.fillRect(0,canvas.width,canvas.height); // context.fillRect(x,y,width,height);
  10. }
  1. <canvas id="canvas" width="600px" height="600px"></canvas>

(这是the fastest of the 2 samples).

或者,尝试手动执行:

  1. var canvas = document.getElementById("canvas"),img = new Image();
  2.  
  3. img.src = 'https://www.google.nl/images/srpr/logo3w.png';
  4.  
  5. img.onload = function(){
  6. for (var w = 0; w < canvas.width; w += img.width) {
  7. for (var h = 0; h < canvas.height; h += img.height) {
  8. context.drawImage(img,w,h);
  9. }
  10. }
  11. }
  1. <canvas id="canvas" width="600px" height="600px"></canvas>

猜你在找的HTML5相关文章