Can I make Canvas to work with Ionic?
It`s not working or showing any graphics.
Am I missing something??
If you had a canvas somewhere within your <ion-content>
like this:
<canvas id="page-6-canvas">
</canvas>
…you can then get the element, canvas and context like this:
canvasElement = angular.element(document.querySelector('#page-6-canvas'));
canvas = canvasElement[0];
context = canvas.getContext('2d');
You can bind to events like:
//touch event handler. only use first touch in array. drawmark where touch occurred.
canvasElement.bind("touchstart", function (event) {
var coord = canvas.relativeCoords(event.targetTouches[0]);
// coord[0], coord[1] contain x and y
});
//mousedown event handler. drawMark where click occurred.
canvasElement.bind("mousedown", function (event) {
var coord = canvas.relativeCoords(event);
});
…you’ll need this helper function somewhere globally too:
HTMLCanvasElement.prototype.relativeCoords = function(event) {
//from: https://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element
var x,y;
//This is the current screen rectangle of canvas
var rect = this.getBoundingClientRect();
var top = rect.top;
var bottom = rect.bottom;
var left = rect.left;
var right = rect.right;
//Recalculate mouse offsets to relative offsets
x = event.clientX - left;
y = event.clientY - top;
//Also recalculate offsets of canvas is stretched
var width = right - left;
//I use this to reduce number of calculations for images that have normal size
if(this.width!=width) {
var height = bottom - top;
//changes coordinates by ratio
x = x*(this.width/width);
y = y*(this.height/height);
}
//Return as an array
return [x,y];
};