I have a view file, "show.html.erb", and a Javascript file, "coordinate.js".
In coordinate.js" I have methods to calculate the width and height of an image.
How can I call those methods on the "Canvas" in my view.
And, below you can find the scripts of the two files:
* show.html.erb
<%= javascript_include_tag "coordinate" %> <canvas id="draw" height= "512" width="512"> </canvas> <p id="notice"><%= notice %></p> <p> <b> Name </b> <%= @dicom.name %> </p> <p> <b> Image </b> </p> <div id="image_element" style="display: none;"> <p> <%= image_tag @dicom.photo.url , :id => 'dicom_image' %> </p> </div> <%= update_page_tag do |page| page << "drawImg();" end %> <%= update_page_tag do |page| page << "drawLine();" end %> <%= link_to 'Edit', edit_dicom_path(@dicom) %> <%= link_to 'Back', dicoms_path %>
* coordinate.js
function getWidth() { var image = document.getElementById("dicom_image"); imageWidth = image.width; return imageWidth; //alert("Image Width is " + image.width); }
function getHeight(){ var image = document.getElementById("dicom_image"); imageHeight = image.height; return imageHeight; //alert("Image Height is " + image.height); }
function imageWidthAndHeight() { getWidth(); getHeight(); }
function getTopLeftCoordinate() { x=document.getElementById('dicom_image').offsetLeft y=document.getElementById('dicom_image').offsetTop alert(x); alert(y); }
function getLeftCoordinate() { left=document.getElementById('dicom_image').offsetLeft return left; }
function getTopCoordinate() { top= document.getElementById('dicom_image').offsetTop return top; }
function drawImg(){ var canvas = document.getElementById("draw"); var context = canvas.getContext("2d"); var image = document.getElementById("dicom_image"); // render the image to the canvas., an then specify the coordinates //(x,y) that specify where the image will be located at the canvas context.drawImage(image, 0, 0); }
function drawLine(){ var canvas = document.getElementById('draw'); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(getLeftCoordinate(), getTopCoordinate()); context.lineTo(100, 200); context.strokeStyle = "#FFF" context.stroke(); }
Thanks.