InfoHeap
Tech
Navigation
  • Home
  • Tutorials
    • CSS tutorials & examples
    • CSS properties
    • Javascript cookbook
    • Linux/Unix Command Line
    • Mac
    • PHP
      • PHP functions online
      • PHP regex
    • WordPress
  • Online Tools
    • Text utilities
    • Online Lint Tools
search

HTML5 Canvas

  • canvas introduction
  • canvas line
  • canvas rectangle
  • canvas clear rectangle
  • canvas to png
  • canvas draw image
  • canvas draw image using base 64 string
  • canvas draw image using svg string
  • canvas svg xml text to png image
 
  • Home
  • > Tutorials
  • > HTML
  • > HTML5 Canvas

HTML5 canvas – draw image using svg xml string

By admin on Jan 30, 2016

HTML5 canvas can be used to draw image from svg xml string using drawImage(). For this the image source should be data:image/svg+xml;charset=utf-8,SVG_STRING. Here is code snippet to show how it works.

<canvas id="canvas1" width="200" height="100" style="background-color:lightgray;"></canvas>
<script type="text/javascript">
window.addEventListener("load", draw);
function draw() {
  var ctx = document.querySelector('#canvas1').getContext('2d');
  var img1 = new Image();
  img1.onload = function() {
    ctx.drawImage(img1, 30, 10);
  }
  img1.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="110" height="60"><rect width="100" height="50" style="fill:green;" /><text x="20" y="20" style="font-size:14px;fill:white;">Hello</text></svg>');
}
</script>
refresh done
try it online

Note that ctx.drawImage() is called on img.onload to ensure image is loaded at the time of drawing image.

Suggested posts:

  1. Convert svg xml text to png image using canvas
  2. PHP – call a function with arguments in array examples
  3. how to debug javascript in Chrome
  4. HTML5 canvas rectangle example
  5. HTML5 shadow dom example
  6. Javascript DOMContentLoaded listener example
  7. HTML5 canvas draw image examples
  8. HTML5 canvas line example
Share this article: share on facebook share on linkedin tweet this submit to reddit
Posted in Tutorials | Tagged HTML5, HTML5 Canvas, Javascript, SVG, Web Development
  • Browse content
  • Article Topics
  • Article archives
  • Contact Us
Popular Topics: Android Development | AngularJS | Apache | AWS and EC2 | Bash shell scripting | Chrome developer tools | Company results | CSS | CSS cookbook | CSS properties | CSS Pseudo Classes | CSS selectors | CSS3 | CSS3 flexbox | Devops | Git | HTML | HTML5 | Java | Javascript | Javascript cookbook | Javascript DOM | jQuery | Kubernetes | Linux | Linux/Unix Command Line | Mac | Mac Command Line | Mysql | Networking | Node.js | Online Tools | PHP | PHP cookbook | PHP Regex | Python | Python array | Python cookbook | SEO | Site Performance | SSH | Ubuntu Linux | Web Development | Webmaster | Wordpress | Wordpress customization | Wordpress How To | Wordpress Mysql Queries | InfoHeap Money

Copyright © 2025 InfoHeap.

Powered by WordPress